/** \file
* Definitions for the portable Mutex class.
* This file is part of Chorus, available at
* http://code.google.com/p/chorus-twitter/ . This file and all associated files
* and derivative works are bound by the terms of the LGPL 3.0 license,
* available at http://www.gnu.org/licenses/lgpl-3.0-standalone.html .
* \par Subversion URL:
* \$URL: http://chorus-twitter.googlecode.com/svn/branches/cpp/src/system/Mutex.hpp $
* \version \$Rev: 152 $
* \date    \$Date: 2010-04-06 07:35:13 +0000 (Tue, 06 Apr 2010) $
*/

#pragma once

#ifdef WIN32
#	include <windows.h>
#endif

#ifdef POSIX
#	include <pthread.h>
#endif

/// The portable mutex class. Uses win32 or pthreads.
class Mutex
{
public:
	/// The constructor.
	Mutex();
	/// The destructor.
	~Mutex();

public:
	/// Lock the mutex. If someone else has a lock this blocks until the other
	/// owner gives it up.
	/// \return True for success.
	bool lock();

#if defined(__unix__) || defined(WIN32)
	/// Wait to lock the mutex until a timeout elapses.
	/// \param timeoutms The number of milliseconds to wait.
	/// \return True for success. False for failure or timeout.
	bool lock(unsigned timeoutms);
#endif

#if defined(__unix__)
	/// Wait to lock the mutex until a timeout elapses.
	/// \param timeoutts The timespec representing the time to wait.
	/// \return True for success. False for failure or timeout.
	bool lock(timespec timeoutts);
#endif
	
#ifdef POSIX
	/// Get the internal mutex object.
	/// \return The pthread mutex object.
	pthread_mutex_t getMutex() const
	{
		return mutex;
	}
#endif

	/// Unlock the mutex.
	/// \return True for success.
	bool unlock();

private:
#ifdef WIN32
	/// The Windows mutex.
	HANDLE mutex;
#endif

#ifdef POSIX
	/// The posix mutex.
	pthread_mutex_t mutex;
#endif
};
